<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/18
 * Time: 18:22
 */

namespace app\index\controller;
use think\Request;
use think\Exception;
use think\Db;

class WeChat
{
    // 微信登录
    public function obtain()
    {
        // 获取参数
        $data = Request::instance()->param();
        writeLog(json_decode($data));
        if (empty($data['token']) || empty($data['openid'])) throw new Exception('not Empty');

        // 解析微信
        $arr = json_decode(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['token'] . '&openid=' . $data['openid']), true);
        writeLog(json_decode('arr'.$arr));
        // halt($arr);

        if (empty($arr['openid'])) return ['code' => 400, 'message' => '解析失败'];

        // 读取是否存在
        $id = Db::name('member')->where(['unionid' => $arr['unionid']])->value('id');

        // 如果不存在
        if (empty($id)) {

            return ['code' => 403, 'message' => '用户未注册', 'unionid' => $arr['unionid'], 'headimgurl' => $arr['headimgurl'], 'nickname' => $arr['nickname'], 'sex' => $arr['sex']];

        }

        return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $id]];

        // // 启动事务
        // Db::startTrans();
        //
        // try {
        //
        //     $user_id = Db::name('member')->insertGetId([
        //         'wechat_id'   => $arr['unionid'],
        //         'avatar'      => $arr['headimgurl'],
        //         'nickname'    => str_replace("馃挀", "", $arr['nickname']),
        //         'sex'         => $arr['sex'],
        //         'create_ip'   => getIP(),
        //         'create_time' => time(),
        //     ]);
        //
        //
        //     // 提交事务
        //     Db::commit();
        //
        //     return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
        //
        // } catch (\Exception $e) {
        //
        //     // 回滚事务
        //     Db::rollback();
        //
        //     return ['code' => 401, 'message' => '网络繁忙'];
        // }

        // }

    }


    public function obtain_zhuce()
    {
        $data = Request::instance()->param();
        writeLog('ijson-'.json_encode($data));
        if (!$data['unionid'] || !$data['tel'] || !$data['password']) return ['code' => 403, 'message' => '参数错误'];

        $tel = Db::name('member')->where('username', $data['tel'])->value('id');
        $name = date('Ymd') . DS . md5(microtime(true)) . ".jpg";
        $path = "./uploads/";
        $map = "/uploads/" . $name;
        put_file_from_url_content($data['headimgurl'], $name, $path);
        if (!$tel) {


            // 启动事务
            Db::startTrans();

            try {
                $user_id = Db::name('member')->insertGetId([
                    'wechat_id'   => $data['unionid'],
                    'avatar'      => $map,
                    'nickname'    => str_replace("馃挀", "", $data['nickname']),
                    'sex'         => $data['sex'],
                    'create_ip'   => getIP(),
                    'create_time' => date('Y-m-d H:i:s',time()),
                    'username'    => $data['tel'],
                    'password'    => sha1($data['password']),
                ]);

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 402, 'message' => $e->getMessage()];
            }
        }else{
            $adf = Db::name('member')->where('username',$data['tel'])->update([
                'wechat_id'   => $data['unionid'],
                'avatar'      => $map,
                'nickname'    => str_replace("馃挀", "", $data['nickname']),
                'sex'         => $data['sex'],
                'create_ip'   => getIP(),
                'create_time' => date('Y-m-d H:i:s',time()),
                'password'    => sha1($data['password']),
            ]);
            writeLog('json'.json_encode($adf));
            $user_id = Db::name('member')->where('username',$data['tel'])->value('id');
            if($adf) return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
            if(!$adf) return ['code' => 401, 'message' => '注册失败'];
        }


    }
}